<?php


namespace app\http\middleware;


use app\services\user\UserService;
use exceptions\AuthException;
use services\CacheService;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use app\Request;
use utils\JwtAuth;

/**
 * token验证中间件
 * Class AuthTokenMiddleware
 * @package app\http\middleware
 */
class AuthTokenMiddleware
{
    /**
     * Description:
     *
     * @param Request  $request
     * @param \Closure $next
     * @param bool     $force
     *
     * @return mixed
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function handle($request, \Closure $next, bool $force = true)
    {
        $authInfo = null;
        $token    = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
        if (!$token)
            $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版，删除此行，某些服务器无法获取到token调整为 Authori-zation
        try {
            /** @var UserService $service */
            $service = app()->make(UserService::class);
            $authInfo = $service->parseToken($token);
        } catch (AuthException $e) {
            if ($force) {
                return app('json')->code($e->getCode())->make($e->getCode(), $e->getMessage());
            }
        }

        if (isset($authInfo['user']) && $authInfo['user']->status === 0) {
            $authInfo['tokenData']->delete();
            return app('json')->code(410004)->make(410004, '账户已被冻结,请联系管理员！');
        }
        Request::macro('user', function () use (&$authInfo) {
            return $authInfo['user'] ?? [];
        });
        Request::macro('tokenData', function () use (&$authInfo) {
            return $authInfo['tokenData'] ?? [];
        });
        Request::macro('isLogin', function () use (&$authInfo) {
            return !is_null($authInfo);
        });
        Request::macro('uid', function () use (&$authInfo) {
            return is_null($authInfo) ? 0 : ($authInfo['user']->uid ?? $authInfo['user']['uid']);
        });
        return $next($request);
    }
}